class FilterScript(object):
   def __init__(self, expr, newexpr='', globals=None):
      self.expr = expr
      self.newexpr = newexpr
      self.globals = {} if globals is None else globals
      
   def __call__(self, model, x):
      return eval(self.expr, self.globals, {'x': x, 'model': model})
      
   def insert(self, model, row):
      model.insertRow(row)
      exec(self.newexpr, self.globals, {'x': model.rows[row], 'model': model})

all = FilterScript('True')
issection = FilterScript('x.level == "section"', 'x.level = "section"')
isactive = FilterScript('model.active[x]', 'model.active[x] = True')
      
class insection(object):
   def __init__(self, section):
      self.section = section
      
   def _sectionindeces(self, model):
      sp = model.rows.index(self.section) + 1
      for i in xrange(sp, len(model.rows)):
         if model.rows[i].level == 'section':
            return sp, i
      return sp, len(model.rows)
      
   def __call__(self, model, x):
      sp, ep = self._sectionindeces(model)
      for item in model.rows[sp:ep]:
         if x is item:
            return True
      return False
      
   def insert(self, model, row):
      sp, ep = self._sectionindeces(model)
      if row > ep: row = ep
      if row < sp: row = sp
      model.insertRow(row)
